﻿/*****************************************介绍*****************************************
 * 作者：User
 * 创建时间：2025-06-09 11:16:13
 * 功能：统一原生交互
**************************************************************************************/

using AppsFlyerSDK;
using Game.Framework;
using Game.Framework.Utility;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;

public class NativeInteraction : BaseManager<NativeInteraction>
{
    private INativeAPI m_NativeAPI;

    private NativeInteraction()
    {
#if UNITY_IOS
        m_NativeAPI = new IosNative();
#elif UNITY_ANDROID
        m_NativeAPI = new AndroidNative();
#endif
    }

    /// <summary>触发当前设备的震动反馈效果</summary>
    public void TriggerVibration(VibrationType type = VibrationType.Soft) => m_NativeAPI.TriggerVibration(type);

    /// <summary>当前设备是否有Sim卡（手机卡）</summary>
    public bool HasSimCard() => m_NativeAPI.HasSimCard();

    /// <summary>显示插屏广告</summary>
    public void ShowIntAd(ETriggerAdType type)
    {
        GameDataMgr.Instance.TriggerAdType = type;
        m_NativeAPI.ShowIntAd();
    }

    /// <summary>显示激励广告</summary>
    public void ShowRewardAd(ETriggerAdType type)
    {
        GameDataMgr.Instance.TriggerAdType = type;
        m_NativeAPI.ShowRewardAd();
    }

    /// <summary>显示自己的插屏广告（游戏内拉取插屏广告库存不足时调用这个方法）</summary>
    public void ShowIntAd_Self() => m_NativeAPI.ShowSelfntAd();

    /// <summary>显示自己的激励广告（游戏内拉取插屏广告库存不足时调用这个方法）</summary>
    public void ShowRewardAd_Self() => m_NativeAPI.ShowSelfRewardAd();

    /// <summary>获取设备ID</summary>
    public string GetDeviceId() => m_NativeAPI.GetDeviceId();

    /// <summary>获取当前应用的Token（该Token是用于绑定App的唯一标识，用于通知等操作）</summary>
    public string GetAppToken() => m_NativeAPI.GetAppToken();

    /// <summary>给H5SDK上报数据</summary>
    public void ReportToH5(string data) => m_NativeAPI.ReportToH5(data);

    public void SendBILog(string eventName, Dictionary<string, object> data)
    {
        if (string.IsNullOrWhiteSpace(eventName) || data == null) return;
        m_NativeAPI.SendBILog(eventName, JsonConvert.SerializeObject(data, Formatting.None));
    }

    /// <summary>设置玩家属性（设置给BI）</summary>
    public void SetUserProperty(string value) => m_NativeAPI.SetUserProperty(value);

    /// <summary>获取IDFA字符串（设置玩家属性时使用）</summary>
    public string GetIdfa() => m_NativeAPI.GetIdfa();

    /// <summary>保存图片到相册</summary>
    public void SaveImageToAlbum(string path) => m_NativeAPI.SaveImageToAlbum(path);

    /// <summary>保存视频到相册</summary>
    public void SaveVideoToAlbum(string path) => m_NativeAPI.SaveVideoToAlbum(path);

    public void Clear() => m_NativeAPI.Clear();

    public void BIUploadPanelOpen(string panelName)
    {
        var data = new Dictionary<string, object> {
            { "page_name", panelName}
        };
        SendBILog("page_view_customize", data);
    }

    public void SendUserProperty()
    {
        Dictionary<string, object> sendData = new Dictionary<string, object>
        {
            {"idfa", GetIdfa() },
            {"user_id",GameDataMgr.Instance.Uid.ToString() },
            {"level", GameDataMgr.Instance.CurLevel},
            {"coins", GameDataMgr.Instance.TotalCoinsNum},
            {"stars", GameDataMgr.Instance.TotalStarNum},
        };
        SetUserProperty(JsonConvert.SerializeObject(sendData));
    }

    /// <summary>行为上报</summary>
    public void BehaviorReporting(string eventName, JObject eventData)
    {
        eventData.Add("uid", GameDataMgr.Instance.Uid);
        var data = new CommonMono.NetPostData();
        data.url = $"{GlobalFixedString.REQ_URL}/event/report";
        data.reqHeaders = new JObject()
        {
            {"Content-Type", "application/json" },
            {"Product", GlobalFixedString.PRODUCT_NAME }
        };
        data.reqParams = new JObject()
        {
            { "platform", TextUtil.GetPlatformShortName() },
            { "device_id", GetDeviceId() },
            { "event_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
            { "event_name", eventName },
            { "event_data", eventData },
        };
        data.callBack = par => LogManager.Log("reporting success", "BehaviorReporting");
        data.failCallBack = err => LogManager.Log($"reporting failed, err:{err}", "BehaviorReporting");
        data.isEncrypt = true;
        CommonMono.Instance.SendPostReqest(data);
    }

    /// <summary>给AF上报数据</summary>
    public void AFUploadData(string eventName, Dictionary<string, string> data)
    {
        AppsFlyer.sendEvent(eventName, data);
        LogManager.Log($"af, eventName:{eventName} data:{JsonConvert.SerializeObject(data, Formatting.None)}", "upload");
    }

    /// <summary>给AF上报广告相关数据</summary>
    public void AFUploadAd(string eventName, double revenue)
    {
        var send = new Dictionary<string, string>
        {
            { "af_currency", "USD" },
            { "af_revenue",  revenue.ToString(System.Globalization.CultureInfo.InvariantCulture)},
            { "customer_user_id", GameDataMgr.Instance.Uid.ToString() },
        };
        AFUploadData(eventName, send);
    }
}